package com.mdg.nfc;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;

public class NFCReadActivity extends Activity {

    private TextView mNFCInfoTv;
    private NfcAdapter nfcAdapter;
    private String readResult = "";
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;    // 意图过滤 想要响应的意图
    private String[][] mTechLists;  // 允许扫描的标签类型
    private boolean isFirst = true;
    private Button mWriteBtn;
    private IntentFilter ndef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfcread);

        //该方法完成接收到Intent时的初始化工作
        init();
    }

    private void init() {
        mWriteBtn = (Button) findViewById(R.id.btn_write);
        mWriteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(NFCReadActivity.this, NFCWriteActivity.class);
                startActivity(intent);
            }
        });
        mNFCInfoTv = (TextView) findViewById(R.id.tv_show_info);
        //NFC适配器，所有的关于NFC的操作从该适配器进行
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (!ifNFCUse()) {
            return;
        }
        //将被调用的Intent，用于重复被Intent触发后将要执行的跳转  设置成single_top 避免重复入栈
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        //设定要过滤的标签动作，这里只接收ACTION_NDEF_DISCOVERED类型
        ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[]{ndef};// 过滤器
        mTechLists = new String[][]{new String[]{NfcA.class.getName()},
                new String[]{NfcF.class.getName()},
                new String[]{NfcB.class.getName()},
                new String[]{NfcV.class.getName()}};// 允许扫描的标签类型

        if (isFirst) {
            if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent()
                    .getAction())) {
                System.out.println(getIntent().getAction());
                if (readFromTag(getIntent())) {
                    mNFCInfoTv.setText(readResult);
                } else {
                    mNFCInfoTv.setText("标签数据为空");
                }
            }
            isFirst = false;
        }
    }

    /**
     *   如果在清单文件中添加过滤  那么会自动响应该页面
     *   如果只在当前页面显示时注册意图  那么只在当前页可以读取
     */
    @Override
    protected void onResume() {
        super.onResume();
        // 前台分发系统,这里的作用在于第二次检测NFC标签时该应用有最高的捕获优先权.
        if(nfcAdapter!=null&&nfcAdapter.isEnabled())
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,mTechLists);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(nfcAdapter!=null&&nfcAdapter.isEnabled())
            nfcAdapter.disableForegroundDispatch(this);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())||
                NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            if (readFromTag(intent)) {
                mNFCInfoTv.setText(readResult);
            } else {
                mNFCInfoTv.setText("标签数据为空");
            }
        }

    }
    //  判断是否具备NFC读写功能
    private boolean ifNFCUse() {
        if (nfcAdapter == null) {
            mNFCInfoTv.setText("设备不支持NFC！");
//            finish();
            return false;
        }
        if (nfcAdapter != null && !nfcAdapter.isEnabled()) {
            mNFCInfoTv.setText("请在系统设置中先启用NFC功能！");
//            finish();
            return false;
        }
        return true;
    }

    private boolean readFromTag(Intent intent) {
        Parcelable[] rawArray = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawArray != null) {
            NdefMessage mNdefMsg = (NdefMessage) rawArray[0];
            NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];
            try {
                if (mNdefRecord != null) {
                    readResult = new String(mNdefRecord.getPayload(), "UTF-8");
                    return true;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return false;
        }
        return false;
    }
}
